package core

import (
	"log"
	"math"
	"time"
)

// AddHealthyTask
//
//	@Description: 添加健康检查任务
//	@receiver this
func (this *LoadBalance) AddHealthyTask() {
	this.task.AddFunc(HealthyTaskSpec, func() {
		for i := 0; i < len(this.Servers); i++ {
			var instanceId = this.Servers[i].InstanceId
			timeUnix := time.Now().Unix()
			if timeUnix > this.Servers[i].nextHealthyTimes {
				//如果当前时间戳小于下一次失效时间戳就跳过
				if timeUnix < this.Servers[i].nextFailureTimes {
					continue
				}
				this.instanceRWLock.Lock()
				//计算降权
				failureWeight := int64(math.Floor(float64(this.Servers[i].Weight)) * (1 / this.Servers[i].FailureFactor))
				if failureWeight == 0 {
					failureWeight = 1
				}
				this.Servers[i].FailureWeight += failureWeight
				//下一次失效检查时间戳
				this.Servers[i].nextFailureTimes = timeUnix + this.Servers[i].HealthyTime
				//如果失效权重大于等于当前权重则移除实例
				if this.Servers[i].FailureWeight >= this.Servers[i].Weight {
					log.Println("rm instance ", instanceId)
					this.Servers = append(this.Servers[:i], this.Servers[i+1:]...)
					i--
				}
				//重新计算总权重
				this.sumWeight()
				//解锁
				this.instanceRWLock.Unlock()
			}
		}
		//如果没有可用的服务则停止任务调度 删除 注册表
		if len(this.Servers) == 0 {
			log.Println("rm server register table")
			this.task.Stop()
			service.Delete(this.key)
		}
	})
}
